package com.qdsg.ysg.doctor.ui;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ainemo.sdk.otf.MakeCallResponse;
import com.ainemo.sdk.otf.NemoSDK;
import com.qdsg.ysg.doctor.R;
import com.qdsg.ysg.doctor.base.BaseActivity;
import com.qdsg.ysg.doctor.base.BaseApplication;
import com.qdsg.ysg.doctor.eventbus.WebSocket;
import com.qdsg.ysg.doctor.eventbus.WebSocketWrapper;
import com.qdsg.ysg.doctor.ui.activity.mine.SignatureActivity;
import com.qdsg.ysg.doctor.ui.activity.mine.SignatureSettingActivity;
import com.qdsg.ysg.doctor.ui.activity.prescription.AddCaseActivity;
import com.qdsg.ysg.doctor.ui.activity.prescription.AtyOrderMedicineDetailActivity;
import com.qdsg.ysg.doctor.ui.adapter.MedicineChatAdapter;
import com.qdsg.ysg.doctor.ui.dialog.ApplyPermissionDialog;
import com.qdsg.ysg.doctor.ui.dialog.Finish2Dialog;
import com.qdsg.ysg.doctor.ui.dialog.FinishDialog;
import com.qdsg.ysg.doctor.ui.dialog.RefundDialog;
import com.qdsg.ysg.doctor.ui.dialog.SelectPicModeDialog;
import com.qdsg.ysg.doctor.ui.dialog.SignatureDialog;
import com.qdsg.ysg.doctor.ui.widget.AudioRecorderButton;
import com.qdsg.ysg.doctor.ui.xylink.XyCallActivity;
import com.qdsg.ysg.doctor.util.DpUtil;
import com.qdsg.ysg.doctor.util.ImageLoaderHelper;
import com.qdsg.ysg.doctor.util.PermissionsChecker;
import com.qdsg.ysg.doctor.util.SoftKeyboardUtil;
import com.qdsg.ysg.doctor.util.TimeUtil;
import com.qdsg.ysg.doctor.util.ToastUtil;
import com.qdsg.ysg.doctor.util.UIConstants;
import com.qdsg.ysg.doctor.util.UriUtils;
import com.qdsg.ysg.doctor.util.UtilString;
import com.rest.business.RestProxy;
import com.rest.exception.BusinessException;
import com.rest.response.AccountRespnonse;
import com.rest.response.AuthOauthVo;
import com.rest.response.BaseResponse;
import com.rest.response.BaseStringResponse;
import com.rest.response.ChatResponse;
import com.rest.response.ConsultOrderDetailResponse;
import com.rest.response.ConsultOrderFinishResponse;
import com.rest.response.OauthStatusResponse;
import com.rest.response.PicUploadResponse;
import com.rest.response.Prescription2Response;
import com.rest.response.UserInfoBean;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.LogUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.qdsg.ysg.doctor.ui.AddRegistrationActivity.REQUEST_GALLERY;
import static com.qdsg.ysg.doctor.ui.AddRegistrationActivity.REQUEST_OPEN_CAMERA;

/**
 * @Description
 * @Author WuJianFeng
 * @Date 2022/8/8 10:36
 */
public class ConsultOrderChatActivity extends BaseActivity {

    @BindView(R.id.chat_recyclerView)
    RecyclerView rvChat;
    @BindView(R.id.photo_recyclerView)
    RecyclerView photo_recyclerView;
    @BindView(R.id.btn_send)
    TextView btnSend;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_oneselfState)
    TextView tv_oneselfState;
    @BindView(R.id.btn_show)
    CheckBox btn_show;
    @BindView(R.id.top)
    LinearLayout top;
    @BindView(R.id.edt_content)
    EditText edtContent;
    @BindView(R.id.tv_patient_detail)
    TextView tv_patient_detail;
    @BindView(R.id.linearLayout)
    LinearLayout linearLayout;
    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;
    @BindView(R.id.tv_pass)
    TextView tv_pass;
    @BindView(R.id.tv_allergy)
    TextView tv_allergy;
    @BindView(R.id.tv_close)
    TextView tv_close;
    @BindView(R.id.tv_wait)
    LinearLayout tv_wait;
    @BindView(R.id.bottom)
    ConstraintLayout bottom;
    @BindView(R.id.tv_time)
    TextView tv_time;
    @BindView(R.id.tv_remain_time)
    TextView tv_remain_time;
    @BindView(R.id.remain_time_container)
    ConstraintLayout remain_time_container;
    @BindView(R.id.pass_container)
    LinearLayout pass_container;
    @BindView(R.id.allergy_container)
    LinearLayout allergy_container;
    @BindView(R.id.btn_end)
    TextView btn_end;
    @BindView(R.id.btn_yuyin)
    AudioRecorderButton btn_yuyin;
    @BindView(R.id.btn_add)
    ImageView btnAdd;
    @BindView(R.id.nested_scrollView)
    NestedScrollView nestedScrollView;
    @BindView(R.id.btn_add_photo)
    ImageView btnAddPhoto;
    @BindView(R.id.btn_video)
    ImageView btnVideo;
    @BindView(R.id.btn_prescription)
    ImageView btnPrescription;
    @BindView(R.id.tv1)
    TextView tv1;
    @BindView(R.id.btn_history)
    ImageView btnHistory;
    @BindView(R.id.btn_refund)
    ImageView btnRefund;
    @BindView(R.id.yuyin)
    ImageView yuyin;

    private PhotoAdapter adapter;
    private ChatAdapter chatAdapter;
    private final List<ConsultOrderDetailResponse.ConsultOrderDetailDataBean.resultListBean> photoList = new ArrayList<>();
    private final List<ChatResponse.Message> messageList = new ArrayList<>();

    private String patientUserId, doctorUserId, doctorId, diagnoseId, patientId, createTime, acceptTime;
    private String patAccount, resourceId, doctorName, patientName, sex, pAge, patientAvatar, doctorPicture, orderNumber;
    private int flag, type, chatFlag, diagnoseFlag, diagType, oFlag, readyFlag, orderStatus;

    private boolean isMeeting = false, isFromCloudList = false;
    private MediaPlayer mediaPlayer;

    //原图像 URI
    private Uri imgUriOri;
    //原图像 路径
    private String imgPathOri;
    // 所需的全部权限
    private final String[] PERMISSIONS = new String[]{
            Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE
    };
    private final String[] VOICEPERMISSIONS = new String[]{
            Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    private final String[] VIDEOPERMISSIONS = new String[]{
            Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA
    };
    private PermissionsChecker mPermissionsChecker; // 权限检测器


    private ProgressDialog dialog;
    private ProgressDialog dialogHuaWei;


    private int current = 1;
    private FinishDialog mFinishDialog;
    private Finish2Dialog mFinish2Dialog;
    private String patientSex;
    private ConsultOrderDetailResponse.ConsultOrderDetailDataBean registrationDetail;

    private String videoAccount;

    private boolean showSignDialog = false;

    @Override
    protected void initViews() {
        //咨询订单没有开方
        btnPrescription.setVisibility(View.GONE);
        tv1.setText(R.string.string_nursing_consultation);
        LinearLayoutManager manager = new LinearLayoutManager(ConsultOrderChatActivity.this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        photo_recyclerView.setLayoutManager(manager);
        adapter = new PhotoAdapter();
        photo_recyclerView.setAdapter(adapter);
        photo_recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void onDraw(@NotNull Canvas c, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                super.onDraw(c, parent, state);
            }

            @Override
            public void getItemOffsets(@NotNull Rect outRect, @NotNull View view, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.bottom = 1;
            }
        });
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true);
        linearLayoutManager.setStackFromEnd(true);
        chatAdapter = new ChatAdapter();
        rvChat.setAdapter(chatAdapter);
        rvChat.setLayoutManager(linearLayoutManager);
        btn_show.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                btn_show.setText("展开");
                pass_container.setVisibility(View.GONE);
                allergy_container.setVisibility(View.GONE);
            } else {
                btn_show.setText("收起");
                pass_container.setVisibility(View.VISIBLE);
                allergy_container.setVisibility(View.VISIBLE);
            }
        });

        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            current = 1;
            messageList.clear();
            getMessageList();
        });

        btn_yuyin.setAudioFinishRecorderListener((seconds, filePath) -> uploadVideo(filePath, (int) seconds));
        btn_yuyin.setOnLongClickMyListener(() -> {
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
            }
        });
        edtContent.setOnClickListener(v -> {
//            chat_recyclerView.smoothScrollToPosition(0);
            nestedScrollView.postDelayed(() -> {
                nestedScrollView.smoothScrollTo(0, nestedScrollView.getBottom());
                edtContent.setFocusable(true);
                edtContent.setFocusableInTouchMode(true);
                edtContent.requestFocus();
            }, 500);
        });
        edtContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

              rvChat.postDelayed(() -> {
//                    chat_recyclerView.smoothScrollToPosition(0);
                    nestedScrollView.smoothScrollTo(0, nestedScrollView.getBottom());
                    edtContent.requestFocus();
                }, 500);
            }
        });
        mPermissionsChecker = new PermissionsChecker(mContext);
    }


    @Override
    protected void initData() {
        diagnoseId = getIntent().getStringExtra("diagnoseId");
        assert diagnoseId != null;
        oFlag = getIntent().getIntExtra("oFlag", 0);
        isFromCloudList = getIntent().getBooleanExtra("isFromCloudList", false);//如果是从云门诊开始诊断过来的，直接唤起视频
        readyFlag = getIntent().getIntExtra("readyFlag", 0);
        type = getIntent().getIntExtra("type", 0);
        getConsultOrderDetailInfo();
        getPatientAccount();
        EventBus.getDefault().register(this);
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.aty_chat;
    }

    @OnClick({R.id.btn_end, R.id.yuyin, R.id.btn_add, R.id.btn_add_photo, R.id.btn_video, R.id.btn_prescription, R.id.btn_history, R.id.btn_send, R.id.btn_refund})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_end://结束问诊
                showLogoutDialog();
                break;
            case R.id.yuyin:
                checkServiceRunning(mContext);
                // 缺少权限时, 进入权限配置页面
                if (mPermissionsChecker.lacksPermissions(VOICEPERMISSIONS)) {
                    checkVoicePermission();
                } else {
                    if (btn_yuyin.getVisibility() == View.GONE) {
                        btn_yuyin.setVisibility(View.VISIBLE);
                        edtContent.setVisibility(View.GONE);
                        SoftKeyboardUtil.hideSoftKeyboard(mContext);
                    } else {
                        btn_yuyin.setVisibility(View.GONE);
                        edtContent.setVisibility(View.VISIBLE);
                        edtContent.requestFocus();
                    }
                }
                break;
            case R.id.btn_add:
                if (linearLayout.getVisibility() == View.GONE) {
                    linearLayout.setVisibility(View.VISIBLE);
                } else if (linearLayout.getVisibility() == View.VISIBLE) {
                    linearLayout.setVisibility(View.GONE);
                }
                rvChat.scrollToPosition(0);
                nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);//滚动到底部
                break;
            case R.id.btn_add_photo:
                checkServiceRunning(mContext);
                // 缺少权限时, 进入权限配置页面
                if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
                    getPermission();
                } else {
                    showSelectHeadPicDialog();
                }
                break;
            case R.id.btn_video:
                checkServiceRunning(mContext);
                // 缺少权限时, 进入权限配置页面
                if (mPermissionsChecker.lacksPermissions(VIDEOPERMISSIONS)) {
                    checkPermission();
                } else {
                    startCall(videoAccount);
                }

                break;
            case R.id.btn_prescription: // 开处方
//                queryOauthStatus();
                querySignStatus();
                break;
            case R.id.btn_history: //历史病例
                Bundle bundleHistory = new Bundle();
                bundleHistory.putString("patientId", patientId);
                bundleHistory.putString("fromWhere", "ConsultOrderChatActivity");
                startActivity(WebViewActivity.class, bundleHistory);
                break;
            case R.id.btn_send:
                checkServiceRunning(mContext);
                if (TextUtils.isEmpty(edtContent.getText().toString().trim())) {
                    ToastUtil.showToast(mContext, "不能发送空白消息");
                    return;
                }
                @SuppressLint("SimpleDateFormat") SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                ChatResponse.Message myMessage = new ChatResponse().new Message();
                String clientId = TimeUtil.getClientId();
                myMessage.fromType = 1;
                myMessage.content = edtContent.getText().toString();
                myMessage.sendTime = df.format(new Date());
                myMessage.messageId = clientId;
                myMessage.flag = 1;
                messageList.add(0, myMessage);
                chatAdapter.notifyItemInserted(0);
                new Handler().postDelayed(() -> {
                    rvChat.scrollToPosition(0);
                    nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);//滚动到底部

                }, 500);
                WebSocket webSocket = new WebSocket.Builder().content(edtContent.getText().toString()).docId(doctorId).diagnoseId(diagnoseId).from(BaseApplication.currentUserId).to(patientUserId).msgType(0).eventFlag(1).clientId(clientId).build();
                EventBus.getDefault().postSticky(webSocket);
                edtContent.setText("");
                break;
            case R.id.btn_refund:
                showRefundDialog();
                break;
        }
    }

    /*** 退费弹框*/
    private void showRefundDialog() {
        RefundDialog refundDialog = RefundDialog.newInstance();
        refundDialog.setmListener(new RefundDialog.OnItemClickListener() {
            @Override
            public void onConfirm(String reason) {
                consultOrderRefund(reason);
            }

            @Override
            public void onCancel() {

            }
        });
        refundDialog.show(getSupportFragmentManager(), "refundDialog");
    }

    /**
     * 咨询订单退费
     *
     * @param reason 原因
     */
    public void consultOrderRefund(String reason) {
        RestProxy.getInstance().consultOrderRefund(diagnoseId, reason, new Observer<BaseResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                ToastUtil.showToast(mContext, "退费成功");
                finish();
//                getConsultOrderDetailInfo();
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);

            }

            @Override
            public void onComplete() {

            }
        });
    }


    /*** 查询授权状态接口*/
    public void queryOauthStatus() {
        RestProxy.getInstance().queryOauthStatus(new Observer<OauthStatusResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(OauthStatusResponse oauthStatusResponse) {
                jump();
            }

            @Override
            public void onError(Throwable e) {
                if (e instanceof BusinessException) {
                    if (((BusinessException) e).errorCode == 2300) {
                        authOauth();
                    } else {
                        dismissProgressDialog();
                        ToastUtil.onError(mContext, e);
                    }
                }
            }

            @Override
            public void onComplete() {
                dismissProgressDialog();
            }
        });
    }

    public void jump() {
        Bundle bundle = new Bundle();
        if (diagType == UIConstants.ORDER_TYPE_4) {//4：护理咨询
            bundle.putString("patientId", patientId);
            bundle.putSerializable("oneselfState", tv_oneselfState.getText().toString().trim());
            bundle.putString("diagnoseId", diagnoseId);
            startActivity(AddCaseActivity.class, bundle);
//                    startActivityForResult( PrescriptionListActivity.class, bundle, 10001 );
        }
    }


    /*** 授权接口*/
    public void authOauth() {
        RestProxy.getInstance().authOauth(new Observer<AuthOauthVo>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(AuthOauthVo authOauthVo) {
                Bundle bundle = new Bundle();
                bundle.putString("url", authOauthVo.data.oauthURL);
                bundle.putInt("type", 1);
                startActivityForResult(SignatureActivity.class, bundle, 2000);
            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
            }

            @Override
            public void onComplete() {
                dismissProgressDialog();
            }
        });
    }

    //查询是否已实名认证和签名
    public void querySignStatus() {
        showProgressDialog(mContext);
        RestProxy.getInstance().querySignStatus(BaseApplication.currentUserId, new Observer<UserInfoBean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(UserInfoBean userInfoBean) {
                //realNameStatus为0 表示已实名认证  signatureImg不为空表示已签名
                if ("0".equals(userInfoBean.data.realNameStatus) && !TextUtils.isEmpty(userInfoBean.data.signatureImg)) {
                    queryOauthStatus();
                } else {
                    dismissProgressDialog();
                    SignatureDialog mSignatureDialog = SignatureDialog.newInstance();
                    mSignatureDialog.setmListener(new SignatureDialog.OnItemClickListener() {
                        @Override
                        public void onConfirm() {
                            startActivity(SignatureSettingActivity.class);
                        }

                        @Override
                        public void onCancel() {
                        }
                    });
                    mSignatureDialog.show(getSupportFragmentManager(), "mSignatureDialog");
                }
            }


            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
                dismissProgressDialog();
            }

            @Override
            public void onComplete() {

            }
        });
    }


    //患者自述相关
    private void getConsultOrderDetailInfo() {
        RestProxy.getInstance().getConsultOrderDetailInfo(diagnoseId, new Observer<ConsultOrderDetailResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onNext(ConsultOrderDetailResponse consultOrderDetailResponse) {
                registrationDetail = consultOrderDetailResponse.getData();
                orderNumber = consultOrderDetailResponse.getData().getOrderNumber();

//                orderStatus = consultOrderDetailResponse.getData().orderStatus;

                diagType = consultOrderDetailResponse.getData().getDiagType();
                doctorName = consultOrderDetailResponse.getData().getDoctorName();
                patientName = consultOrderDetailResponse.getData().getPatientName();
                sex = consultOrderDetailResponse.getData().getPatientSex();
                pAge = consultOrderDetailResponse.getData().getPatientAge();

                createTime = consultOrderDetailResponse.getData().getCreateTime();
                acceptTime = consultOrderDetailResponse.getData().getAcceptTime();
                patientAvatar = consultOrderDetailResponse.getData().getPatientAvatar();//患者头像

                doctorPicture = consultOrderDetailResponse.getData().getDoctorPicture();
                chatFlag = consultOrderDetailResponse.getData().getFlag();
                patientSex = consultOrderDetailResponse.getData().getPatientSex();

//                patAccount = consultOrderDetailResponse.getData().patAccount;

                tv_time.setText(createTime);
                startCountDownTimer(consultOrderDetailResponse.getData().getRemainingTime());
                patientUserId = consultOrderDetailResponse.getData().getPatientUserId();
                doctorUserId = consultOrderDetailResponse.getData().getDoctorUserId();
                BaseApplication.patientUserId = patientUserId;
                BaseApplication.diagnoseId = diagnoseId;
                doctorId = consultOrderDetailResponse.getData().getDoctorId();
                patientId = consultOrderDetailResponse.getData().getPatientId();
                tv_title.setText(consultOrderDetailResponse.getData().getPatientName());
                if (consultOrderDetailResponse.getData().getResultList() != null) {
                    if (consultOrderDetailResponse.getData().getResultList().size() == 0) {
                        photo_recyclerView.setVisibility(View.GONE);
                    }
                    photoList.clear();
                    photoList.addAll(consultOrderDetailResponse.getData().getResultList());
                    adapter.notifyDataSetChanged();
                }
                StringBuilder sb = new StringBuilder();

                sb.append(consultOrderDetailResponse.getData().getPatientName()).append("  ")
                        .append(consultOrderDetailResponse.getData().getPatientSex()).append("  ")
                        .append(consultOrderDetailResponse.getData().getPatientAge());
                if (!UtilString.isEmpty(consultOrderDetailResponse.getData().getCardType())) {
                    if (UIConstants.CARD_TYPE_1.equals(consultOrderDetailResponse.getData().getCardType())) {
                        sb.append("  自费卡");
                    } else if (UIConstants.CARD_TYPE_2.equals(consultOrderDetailResponse.getData().getCardType())) {
                        sb.append("  社保卡");
                    } else if (UIConstants.CARD_TYPE_3.equals(consultOrderDetailResponse.getData().getCardType())) {
                        sb.append("  双卡");
                    }
                }
                tv_patient_detail.setText(sb.toString());
                tv_oneselfState.setText(consultOrderDetailResponse.getData().getOneselfState());
                tv_pass.setText(TextUtils.isEmpty(consultOrderDetailResponse.getData().getPastHistory()) ? "无" : consultOrderDetailResponse.getData().getPastHistory());
                tv_allergy.setText(TextUtils.isEmpty(consultOrderDetailResponse.getData().getAllergyHistory()) ? "无" : consultOrderDetailResponse.getData().getAllergyHistory());

                Log.e("状态---", diagType + "---" + oFlag);
                if (diagType == UIConstants.ORDER_TYPE_3) {//云门诊，
                    remain_time_container.setVisibility(View.GONE);
                    if (oFlag == 303) {
                        if (isFromCloudList) {
                            dialogHuaWei = ProgressDialog.show(ConsultOrderChatActivity.this, "提示", "正在加载…", true, false, null);

                        }
                        tv_close.setVisibility(View.GONE);
                        bottom.setVisibility(View.VISIBLE);

                    } else if (oFlag == 308) {//308 云门诊医生提交诊断意见或开方后
                        tv_close.setVisibility(View.GONE);
                        bottom.setVisibility(View.VISIBLE);
                        //能视频
                        btnAdd.setVisibility(View.VISIBLE);
                        btn_end.setVisibility(View.VISIBLE);
                    } else if (oFlag == 302) {
                        if (readyFlag == 1) {//已经报道
                            tv_close.setVisibility(View.GONE);
                            bottom.setVisibility(View.VISIBLE);//不能视频
                            btnAdd.setVisibility(View.GONE);
                        } else {//没有报到
                            tv_close.setVisibility(View.VISIBLE);
                            tv_close.setText("当前诊断未开始");
                            bottom.setVisibility(View.INVISIBLE);
                        }

                    } else if (oFlag == 304) {
                        tv_close.setVisibility(View.VISIBLE);
                        tv_close.setText("当前诊断已结束");
                        bottom.setVisibility(View.INVISIBLE);
                    } else {//待就诊
                        tv_close.setVisibility(View.VISIBLE);
                        tv_close.setText("当前诊断未开始");
                        bottom.setVisibility(View.INVISIBLE);
                    }
                } else if (diagType == UIConstants.ORDER_TYPE_4) {//护理咨询
                    btn_end.setVisibility(View.VISIBLE);
                    if (consultOrderDetailResponse.getData().getFlag() == UIConstants.NURSE_CONSULT_ORDER_2) {
                        //已经结束
                        tv_close.setText("当前诊断已结束");
                        tv_close.setVisibility(View.VISIBLE);

                        if (!TextUtils.isEmpty(orderNumber) && orderStatus != 50 && orderStatus != 60) {
                            bottom.setVisibility(View.VISIBLE);
                            btnAddPhoto.setVisibility(View.GONE);
                            btnVideo.setVisibility(View.GONE);
                            btnHistory.setVisibility(View.GONE);
                            btn_yuyin.setVisibility(View.GONE);
                            edtContent.setVisibility(View.GONE);
                            btnSend.setVisibility(View.GONE);
                            btnAdd.setVisibility(View.GONE);
                            yuyin.setVisibility(View.GONE);
                        } else {
                            bottom.setVisibility(View.INVISIBLE);
                        }
                        remain_time_container.setVisibility(View.GONE);
                        btn_end.setVisibility(View.INVISIBLE);
                    }
                }

                if (consultOrderDetailResponse.getData().getFlag() == UIConstants.NURSE_CONSULT_ORDER_0) {
                    //是否结束咨询
                    showLogoutDialog2();
                    remain_time_container.setVisibility(View.GONE);
                }
                flag = consultOrderDetailResponse.getData().getFlag();

                current = 1;
                messageList.clear();
                getMessageList();
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(ConsultOrderChatActivity.this, e);

            }

            @Override
            public void onComplete() {

            }
        });
    }

    /**
     * 获取患者的账号信息
     */
    private void getPatientAccount() {
        RestProxy.getInstance().getPatientAccount(diagnoseId, UIConstants.XY_ACCOUNT_TYPE_2, new Observer<AccountRespnonse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(AccountRespnonse accountRespnonse) {
                videoAccount = accountRespnonse.data;
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void getMessageList() {
//        current++;
        RestProxy.getInstance().getChatList(diagnoseId, current + "", new Observer<ChatResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ChatResponse chatResponse) {
                if (chatResponse.data.records != null) {
                    messageList.addAll(chatResponse.data.records);
                    if (diagType == UIConstants.ORDER_TYPE_4) {
                        if (chatFlag != 0) {
                            if (chatResponse.data.current == chatResponse.data.pages || chatResponse.data.pages == 0) {
                                if (messageList.size() > 0 && messageList.get(messageList.size() - 1).messageType == 10) {
                                    return;
                                }
                                ChatResponse.Message message = new ChatResponse().new Message();
                                message.messageType = 10;
                                messageList.add(message);
                            }
                        }
                    }
                    if (chatFlag == 2) {
                        if (messageList.size() > 0 && messageList.get(0).messageType == 11) {
                            return;
                        }
                        ChatResponse.Message message = new ChatResponse().new Message();
                        message.messageType = 11;
                        messageList.add(0, message);
                    }
                }
                chatAdapter.notifyDataSetChanged();
                if (current == 1) {
                    rvChat.postDelayed(() -> {
                        rvChat.smoothScrollToPosition(0);
                        nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);//滚动到底部
                    }, 1000);
//                    new Handler().postDelayed(() -> {
//                        chat_recyclerView.scrollToPosition(0);
//                        nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);//滚动到底部
//
//                    }, 1000);
                }

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                ToastUtil.onError(mContext, e);
                refreshLayout.finishRefresh(false);
            }

            @Override
            public void onComplete() {
                refreshLayout.finishRefresh(true);
            }
        });
    }

    @SuppressLint("CheckResult")
    private void checkPermission() {
        ApplyPermissionDialog applyPermissionDialog = ApplyPermissionDialog.newInstance("5", true);
        applyPermissionDialog.show(getSupportFragmentManager(), "applyPermissionDialog");
        applyPermissionDialog.setmListener(new ApplyPermissionDialog.OnItemClickListener() {

            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onConfirm() {
                RxPermissions permissions = new RxPermissions(ConsultOrderChatActivity.this);
                permissions.request(VIDEOPERMISSIONS)
                        .subscribe(granted -> {
                            if (granted) {
                                startCall(videoAccount);
                            } else {
                                ToastUtil.showToast(mContext, "请同意语音和存储权限，否则功能无法使用");
                                startNotificationSetting(mContext);
                            }
                        });
            }

            @Override
            public void onCancel() {

            }
        });
    }

    public void startCall(String callNumber) {
        NemoSDK.getInstance().makeCall(callNumber, "", new MakeCallResponse() {
            @Override
            public void onCallSuccess() {
//                // 查询号码成功, 进入通话界面
                Intent callIntent = new Intent(ConsultOrderChatActivity.this, XyCallActivity.class);
                callIntent.putExtra("number", callNumber);
                startActivity(callIntent);
                LogUtil.e("onCallSuccess");
            }

            @Override
            public void onCallFail(String s, String s1) {

            }
        });
    }

    /**
     * 结束咨询订单
     *
     * @time 2020/12/2 17:24
     */
    private void consultOrderFinish() {
        RestProxy.getInstance().consultOrderFinish(diagnoseId, new Observer<ConsultOrderFinishResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ConsultOrderFinishResponse consultOrderFinishResponse) {
                mFinishDialog.dismiss();
                if (mFinishDialog != null) {
                    mFinishDialog = null;
                }
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(ConsultOrderChatActivity.this, e);

            }

            @Override
            public void onComplete() {

            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        //data的返回值根据
        switch (requestCode) {
            case REQUEST_OPEN_CAMERA:
                getPresignedUrl(imgPathOri);
                break;
            case REQUEST_GALLERY:
                if (data != null) {
                    Uri imgUriSel = data.getData();
                    String imgPathSel = UriUtils.formatUri(this, imgUriSel);
                    getPresignedUrl(imgPathSel);
                }
                break;
            case 10000:
            case 10001:
                if (diagType == UIConstants.ORDER_TYPE_4) {
                    getConsultOrderDetailInfo();
                }
                if (diagType == UIConstants.ORDER_TYPE_3) {
                    finish();
                }
                break;
            case 2000:
                jump();
                break;
            default:
                break;
        }
    }


    /**
     * 创建原图像保存的文件
     */
    protected File createOriImageFile() throws IOException {
        @SuppressLint("SimpleDateFormat") String imgNameOri = "HomePic_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File pictureDirOri = new File(Objects.requireNonNull(getExternalFilesDir(Environment.DIRECTORY_PICTURES)).getAbsolutePath() + "/OriPicture");
        if (!pictureDirOri.exists()) {
            pictureDirOri.mkdirs();
        }
        File image = File.createTempFile(
                imgNameOri,         /* prefix */
                ".jpg",             /* suffix */
                pictureDirOri       /* directory */
        );
        imgPathOri = image.getAbsolutePath();
        return image;
    }

    private SelectPicModeDialog mSelectPicModeDialog = null;


    private void showSelectHeadPicDialog() {
        if (mSelectPicModeDialog == null) {
            // 初始化点击头像弹出的对话框
            mSelectPicModeDialog = SelectPicModeDialog.newInstance();
            mSelectPicModeDialog.setOnItemClickListener(new SelectPicModeDialog.OnItemClickListener() {
                @Override
                public void takePhotoClick() {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File oriPhotoFile = null;
                    try {
                        oriPhotoFile = createOriImageFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                        imgUriOri = Uri.fromFile(oriPhotoFile);
                    } else {
                        assert oriPhotoFile != null;
                        imgUriOri = FileProvider.getUriForFile(ConsultOrderChatActivity.this, UIConstants.FILE_PROVIDER_URI, oriPhotoFile);
                    }
//                    phoneCamearUri = FileProvider.getUriForFile(PersonInfoActivity.this,"com.joyoung.robot.phone.provider",file);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUriOri);
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    startActivityForResult(intent, REQUEST_OPEN_CAMERA);
                }

                @Override
                public void pickFromAlbumClick() {
                    @SuppressLint("IntentReset") Intent intent = new Intent(
                            Intent.ACTION_PICK,
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(intent, REQUEST_GALLERY);
                }
            });
        }
        mSelectPicModeDialog.show(getSupportFragmentManager(), "SelectPicModeDialog");
    }

    private void uploadVideo(String imgPathSel, int time) {
        RestProxy.getInstance().uploadVideo(new File(imgPathSel), new Observer<PicUploadResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(PicUploadResponse picUploadResponse) {
                ChatResponse.Message message = new ChatResponse().new Message();
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                message.messageType = 2;
                message.fromType = 1;
                message.content = picUploadResponse.data.shareUrl;
                message.src = picUploadResponse.data.shareUrl;
                message.sendTime = df.format(new Date());
                message.time = time;
                messageList.add(0, message);
                chatAdapter.notifyItemInserted(0);
                new Handler().postDelayed(() -> {
                    rvChat.scrollToPosition(0);
                    nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);//滚动到底部

                }, 500);
                WebSocket webSocket = new WebSocket.Builder().content(picUploadResponse.data.shareUrl).docId(doctorId).diagnoseId(diagnoseId).from(BaseApplication.currentUserId).to(patientUserId).picType("wav").msgType(2).eventFlag(1).clientId(TimeUtil.getClientId()).time(time).build();
                EventBus.getDefault().postSticky(webSocket);
            }

            @Override
            public void onError(Throwable e) {
                dialog.dismiss();
                ToastUtil.onError(ConsultOrderChatActivity.this, e);
            }

            @Override
            public void onComplete() {
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (timer != null) {
            timer.cancel();
        }
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        }
        BaseApplication.patientUserId = "";
        BaseApplication.diagnoseId = "";
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(WebSocket webSocket) {
        if (webSocket.eventFlag == 0) {
            if (TextUtils.isEmpty(webSocket.diagnoseId)) {
                return;
            }
            if (TextUtils.isEmpty(webSocket.content)) {
                return;
            }

            if (webSocket.diagnoseId.equals(diagnoseId)) {
                if (webSocket.msgType != 6) {
                    ChatResponse.Message message = new ChatResponse().new Message();
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                    message.messageType = webSocket.msgType;
                    message.content = webSocket.content;
                    message.src = webSocket.src;
                    message.time = webSocket.time;
                    message.sendTime = webSocket.createTime;
                    message.fromType = 0;
                    messageList.add(0, message);
                    chatAdapter.notifyItemInserted(0);
                    chatAdapter.notifyDataSetChanged();
                    nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);//滚动到底部
                } else {
                    //msgType==6代表处方消息
                    getPrescription(webSocket.preId);
                }
                WebSocket webSocket2 = new WebSocket();
                webSocket2.cmd = 24;
                webSocket2.diagnoseId = webSocket.diagnoseId;
                webSocket2.to = webSocket.to;
                webSocket2.msgId = webSocket.id;
                webSocket2.eventFlag = 4;
                EventBus.getDefault().postSticky(webSocket2);
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent2(WebSocketWrapper webSocket) {
        if (webSocket.cmd == 103) {
            ToastUtil.showToast(mContext, "患者结束咨询");
            finish();
        }
        if (webSocket.cmd == 105 || webSocket.cmd == 30) {
            isMeeting = false;
            finishMeeting();
        } else if (webSocket.code == 10000 || webSocket.code == 10001) {
            for (int i = 0; i < messageList.size(); i++) {
                if (!TextUtils.isEmpty(messageList.get(i).messageId) && messageList.get(i).messageId.equals(webSocket.clientId)) {
                    messageList.get(i).flag = 0;
                    chatAdapter.notifyItemChanged(i);
                    rvChat.scrollToPosition(0);
                    nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);//滚动到底部
                }
            }
        }
    }

    @Override
    public void initBack() {
        btn_back = findViewById(R.id.btn_back);
        if (btn_back != null) {
            btn_back.setOnClickListener(v -> {
                Log.e("btn_back", isMeeting + "");
                finish();
            });
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
            finish();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    /**
     * 查询处方详情
     *
     * @time 2020/8/26 16:52
     */
    private void getPrescription(String preId) {
        RestProxy.getInstance().getPrescription2(preId, new Observer<Prescription2Response>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Prescription2Response prescriptionResponse) {
                ChatResponse.Message message = new ChatResponse().new Message();
                message.messageType = 6;
                message.fromType = 1;
                message.prescription = prescriptionResponse.data;
                messageList.add(0, message);
                chatAdapter.notifyItemInserted(0);
                rvChat.scrollToPosition(0);
                nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);//滚动到底部
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    /**
     * 结束会议
     *
     * @time 2020/8/1 18:46
     */
    private void finishMeeting() {
        if (TextUtils.isEmpty(BaseApplication.conferenceID)) {
            return;
        }
        RestProxy.getInstance().finishMeeting(patientUserId, diagnoseId, BaseApplication.currentUserId, BaseApplication.conferenceID, "0", new Observer<BaseResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                BaseApplication.conferenceID = "";
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }


    @Override
    protected void onNewIntent(Intent intent) {
        Log.e("onnewintent", "onnewintent");
        //移动视频传过来的参数
        long userid = intent.getLongExtra("userid", 0);
        Log.e("", "onNewIntent: " + userid);
        super.onNewIntent(intent);
    }

    private void acceptConsultOrder() {
        RestProxy.getInstance().acceptConsultOrder(diagnoseId, new Observer<BaseResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                current = 1;
                getConsultOrderDetailInfo();
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(ConsultOrderChatActivity.this, e);

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void refuseConsultOrder() {
        RestProxy.getInstance().refuseConsultOrder(diagnoseId, new Observer<BaseResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                finish();
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(ConsultOrderChatActivity.this, e);

            }

            @Override
            public void onComplete() {

            }
        });
    }

    class PhotoAdapter extends RecyclerView.Adapter<PhotoAdapter.Holder> {

        @NotNull
        @Override
        public Holder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            Holder myHolder;
            myHolder = new Holder(LayoutInflater.from(ConsultOrderChatActivity.this).inflate(R.layout.item_photo2, parent, false));
            return myHolder;
        }

        @Override
        public void onBindViewHolder(Holder holder, final int position) {
            holder.itemView.setOnClickListener(v -> {
                Bundle bundle = new Bundle();
                bundle.putString("url", photoList.get(position).getUrl());
                bundle.putInt("type", 1);
                ConsultOrderChatActivity.this.startActivity(BigImageActivity.class, bundle);
            });
            ImageLoaderHelper.getInstance().GlideImageLoader(ConsultOrderChatActivity.this, photoList.get(position).getThumbnailUrl(), holder.img);
        }

        @Override
        public int getItemCount() {
            return photoList.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            ImageView img;

            public Holder(View itemView) {
                super(itemView);
                img = itemView.findViewById(R.id.image);
            }
        }
    }


    class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.Holder> {

        @NotNull
        @Override
        public Holder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            if (viewType == 1) {
                return new Holder(getLayoutInflater().inflate(R.layout.item_chat_right, parent, false));
            } else {
                return new Holder(getLayoutInflater().inflate(R.layout.item_chat_left, parent, false));
            }

        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(Holder holder, int position) {
            holder.itemView.setOnClickListener(v -> {
                if (messageList.get(position).messageType == 1) {
                    Bundle bundle = new Bundle();
                    bundle.putString("url", messageList.get(position).src);
                    bundle.putInt("type", 1);
                    ConsultOrderChatActivity.this.startActivity(BigImageActivity.class, bundle);
                }
            });


            if (getItemViewType(position) == 1) {
                //加载医生自己头像
                if (!UtilString.isEmpty(BaseApplication.avatar)) {
                    ImageLoaderHelper.getInstance().GlideCircleImageLoader(ConsultOrderChatActivity.this, BaseApplication.avatar, holder.img_head);
                } else {
                    if ("女".equals(BaseApplication.sex)) {
                        holder.img_head.setImageDrawable(ContextCompat.getDrawable(ConsultOrderChatActivity.this, R.mipmap.icon_girl));
                    } else {
                        holder.img_head.setImageDrawable(ContextCompat.getDrawable(ConsultOrderChatActivity.this, R.mipmap.icon_boy));
                    }
                }

            } else {
                //加载患者头像
                if (!UtilString.isEmpty(patientAvatar)) {
                    ImageLoaderHelper.getInstance().GlideCircleImageLoader(ConsultOrderChatActivity.this, patientAvatar, holder.img_head);
                } else if ("女".equals(patientSex)) {
                    holder.img_head.setImageDrawable(ContextCompat.getDrawable(ConsultOrderChatActivity.this, R.mipmap.icon_girl));
                } else {
                    holder.img_head.setImageDrawable(ContextCompat.getDrawable(ConsultOrderChatActivity.this, R.mipmap.icon_boy));
                }
            }

            if (messageList.get(position).flag == 0) {
                holder.img_loading.setVisibility(View.GONE);
            } else if (messageList.get(position).flag == 1) {
                holder.img_loading.setVisibility(View.VISIBLE);
                startLoading(holder.img_loading);
            }
            if (messageList.get(position).messageType == 0) {
                holder.yuyin.setVisibility(View.GONE);
                holder.tv_context.setVisibility(View.VISIBLE);
                holder.img.setVisibility(View.GONE);
                holder.begin_container.setVisibility(View.GONE);
                holder.diagnose_container.setVisibility(View.GONE);
                holder.img_head.setVisibility(View.VISIBLE);
                holder.tv_context.setText(messageList.get(position).content);
                holder.tv_time.setText(messageList.get(position).sendTime);
            } else if (messageList.get(position).messageType == 1) {
                holder.yuyin.setVisibility(View.GONE);
                holder.tv_context.setVisibility(View.GONE);
                holder.img_loading.setVisibility(View.GONE);
                holder.begin_container.setVisibility(View.GONE);
                holder.img.setVisibility(View.VISIBLE);
                holder.diagnose_container.setVisibility(View.GONE);
                holder.img_head.setVisibility(View.VISIBLE);
                holder.tv_time.setText(messageList.get(position).sendTime);
                ImageLoaderHelper.getInstance().GlideImageLoader(ConsultOrderChatActivity.this, messageList.get(position).content, holder.img);
            } else if (messageList.get(position).messageType == 6) {
                //处方消息
                holder.yuyin.setVisibility(View.GONE);
                holder.tv_context.setVisibility(View.GONE);
                holder.img.setVisibility(View.GONE);
                holder.diagnose_container.setVisibility(View.VISIBLE);
                holder.begin_container.setVisibility(View.GONE);
                holder.img_loading.setVisibility(View.GONE);
                holder.img_head.setVisibility(View.GONE);
                if (messageList.get(position).sendTime != null) {
                    holder.tv_time.setText(messageList.get(position).sendTime);
                }
                if (messageList.get(position).prescription != null) {
                    holder.tv_null.setVisibility(View.GONE);
                    holder.tv_diagnose_status.setText(messageList.get(position).prescription.pFlagStr);
                    if (messageList.get(position).prescription.passTime != null) {
                        holder.tv_diagnose_time.setVisibility(View.VISIBLE);
                        holder.tv_diagnose_time.setText(messageList.get(position).prescription.passTime);
                    } else {
                        holder.tv_diagnose_time.setVisibility(View.GONE);
                    }
                    Log.e("诊断结果---", messageList.get(position).prescription.diagnoseResult);
                    if (messageList.get(position).prescription.diagnoseResult != null) {
                        holder.tv_diagnose.setText("医生意见：" + messageList.get(position).prescription.diagnoseResult);
                    } else {
                        holder.tv_diagnose.setText("医生意见：" + "无");
                    }
                    if (messageList.get(position).prescription.westernList != null) {
                        MedicineChatAdapter adapter;
                        adapter = new MedicineChatAdapter(ConsultOrderChatActivity.this, messageList.get(position).prescription.westernList);
                        holder.recyclerView.setAdapter(adapter);
                        holder.recyclerView.setLayoutManager(new LinearLayoutManager(ConsultOrderChatActivity.this));
                        holder.recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
                            @Override
                            public void onDraw(@NotNull Canvas c, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                                super.onDraw(c, parent, state);
                            }

                            @Override
                            public void getItemOffsets(@NotNull Rect outRect, @NotNull View view, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                                super.getItemOffsets(outRect, view, parent, state);
                                outRect.bottom = DpUtil.dip2px(ConsultOrderChatActivity.this, 1);
                            }
                        });
                        adapter.notifyDataSetChanged();
                    }
                    holder.itemView.setOnClickListener(v -> {
                        Bundle bundle = new Bundle();
                        bundle.putString("orderId", messageList.get(holder.getAdapterPosition()).prescription.orderId);
                        startActivity(AtyOrderMedicineDetailActivity.class, bundle);
                    });

                } else {
                    holder.tv_null.setVisibility(View.VISIBLE);
                }
            } else if (messageList.get(position).messageType == 10) {
                holder.yuyin.setVisibility(View.GONE);
                holder.img_head.setVisibility(View.GONE);
                holder.tv_context.setVisibility(View.GONE);
                holder.img_loading.setVisibility(View.GONE);
                holder.img.setVisibility(View.GONE);
                holder.diagnose_container.setVisibility(View.GONE);
                holder.begin_container.setVisibility(View.VISIBLE);
                holder.tv_time.setText(acceptTime);
                holder.textView3.setText("问诊开始");
                holder.info1.setText("1、问诊期间，您与医生对话不限次数");
                holder.info2.setText("2、问诊最长24小时，到期将自动结束");
            } else if (messageList.get(position).messageType == 11) {
                holder.yuyin.setVisibility(View.GONE);
                holder.img_head.setVisibility(View.GONE);
                holder.tv_context.setVisibility(View.GONE);
                holder.img_loading.setVisibility(View.GONE);
                holder.img.setVisibility(View.GONE);
                holder.diagnose_container.setVisibility(View.GONE);
                holder.begin_container.setVisibility(View.VISIBLE);
                holder.tv_time.setText(acceptTime);
                holder.textView3.setText("问诊结束");
                holder.info1.setText("1、问诊结论已发出，本次问诊结束");
                holder.info2.setText("2、服务评价、意见反馈请点击表扬与投诉");
            } else if (messageList.get(position).messageType == 2) {
                holder.tv_context.setVisibility(View.VISIBLE);
                holder.img.setVisibility(View.GONE);
                holder.begin_container.setVisibility(View.GONE);
                holder.diagnose_container.setVisibility(View.GONE);
                holder.tv_context.setVisibility(View.GONE);
                holder.tv_time.setText(messageList.get(position).sendTime);
                holder.img_head.setVisibility(View.VISIBLE);
                holder.yuyin.setVisibility(View.VISIBLE);
                holder.yuyin.setText(messageList.get(position).time + "''");
                if (messageList.get(position).isSpeaking) {
                    holder.yuyin.setTextColor(getResources().getColor(R.color.zm_red));
                } else {
                    if (getItemViewType(position) == 1) {
                        holder.yuyin.setTextColor(getResources().getColor(R.color.white));
                    } else {
                        holder.yuyin.setTextColor(getResources().getColor(R.color.mainGreen));
                    }
                }
                holder.yuyin.setOnClickListener(v -> {
                    if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                        mediaPlayer.pause();
                        resetSpeakingPosition();
                    } else {
                        mediaPlayer = new MediaPlayer();
                        try {
                            mediaPlayer.setDataSource(messageList.get(holder.getAdapterPosition()).content);
                            mediaPlayer.prepareAsync(); // 准备文件
                            mediaPlayer.setOnPreparedListener(mp -> {
                                // 装载完毕回调
                                mediaPlayer.start();
                                messageList.get(holder.getAdapterPosition()).isSpeaking = true;
                                notifyItemChanged(holder.getAdapterPosition());
                            });
                            mediaPlayer.setOnCompletionListener(mp -> resetSpeakingPosition());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }

        @Override
        public int getItemViewType(int position) {
            return messageList.get(position).fromType;
        }

        @Override
        public int getItemCount() {
            return messageList.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            TextView tv_time, tv_context, btn_confirm, tv_diagnose, tv_null, tv_diagnose_time, textView3, info1, info2, yuyin, tv_diagnose_status;
            ImageView img, img_loading, img_head;
            LinearLayout diagnose_container, begin_container;
            RecyclerView recyclerView;

            public Holder(View itemView) {
                super(itemView);
                tv_time = itemView.findViewById(R.id.tv_time);
                tv_context = itemView.findViewById(R.id.tv_context);
                btn_confirm = itemView.findViewById(R.id.btn_confirm);
                tv_diagnose = itemView.findViewById(R.id.tv_diagnose);
                diagnose_container = itemView.findViewById(R.id.diagnose_container);
                recyclerView = itemView.findViewById(R.id.recyclerView);
                img = itemView.findViewById(R.id.img);
                img_loading = itemView.findViewById(R.id.img_loading);
                tv_null = itemView.findViewById(R.id.tv_null);
                tv_diagnose_time = itemView.findViewById(R.id.tv_diagnose_time);
                img_head = itemView.findViewById(R.id.img_head);
                begin_container = itemView.findViewById(R.id.begin_container);
                textView3 = itemView.findViewById(R.id.textView3);
                info1 = itemView.findViewById(R.id.info1);
                info2 = itemView.findViewById(R.id.info2);
                yuyin = itemView.findViewById(R.id.yuyin);
                tv_diagnose_status = itemView.findViewById(R.id.tv_diagnose_status);
            }
        }
    }


    private void resetSpeakingPosition() {
        for (int i = 0; i < messageList.size(); i++) {
            messageList.get(i).isSpeaking = false;
        }
        chatAdapter.notifyItemRangeChanged(0, messageList.size());
    }

    private void startLoading(View view) {
        ObjectAnimator anim = ObjectAnimator.ofFloat(view, "rotation", 0f, 360f);

        // 动画的持续时间，执行多久？
        anim.setDuration(1000);
        anim.setRepeatCount(-1);

        // 回调监听
        anim.addUpdateListener(animation -> {
            float value = (Float) animation.getAnimatedValue();
        });

        // 正式开始启动执行动画
        anim.start();
    }

    private CountDownTimer timer;

    private void startCountDownTimer(String remainPayTime) {
        if (TextUtils.isEmpty(remainPayTime) || Long.parseLong(remainPayTime) < 0) {
            return;
        }
        Log.e("倒计时===", remainPayTime);
        final int parseInt = Integer.parseInt(remainPayTime);
        timer = new CountDownTimer(parseInt, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                tv_remain_time.setText(millisUntilFinished / 60000 / 60 + "时" + millisUntilFinished / 60000 % 60 + "分" + (millisUntilFinished / 1000) % 60 + "秒");
            }

            @Override
            public void onFinish() {
            }
        };
        timer.start();
    }

    /**
     * 获取minio服务器域名
     *
     * @time 2020/12/2 10:21
     */
    private void getPresignedUrl(String imgPathSel) {

        dialog = ProgressDialog.show(ConsultOrderChatActivity.this, "提示", "正在上传中…", true, false, null);

        // bucket:   1-病历 2-评论(反馈) 3-头像 4-轮播图 9-聊天图片 ',
        RestProxy.getInstance().getPresignedUrl("9", new Observer<BaseStringResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(BaseStringResponse baseStringResponse) {
                try {
                    String data = baseStringResponse.data;
                    if (data.contains("?")) {
                        String substring = data.substring(0, data.indexOf("?"));
                        resourceId = substring.substring(substring.lastIndexOf("/") + 1);
                        Log.e("presignedUrl -----", resourceId);
                        uploadFileMinio(imgPathSel, data);
                    }

                } catch (Exception e) {
                    // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    e.printStackTrace();
                    //打印出来就Log.e(TAG,Log.getStackTraceString(e));
                }

            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(ConsultOrderChatActivity.this, e);
            }

            @Override
            public void onComplete() {
            }
        });
    }

    /**
     * 上传图片到minio服务器
     * <p>
     * * @time 2020/12/3 15:36
     */
    private void uploadFileMinio(String imgPath, String url) {
        new Thread(() -> {
            try {
                Log.e("TAG-路径-----", imgPath);
                File file = new File(imgPath);
                FileInputStream fileInputStream = new FileInputStream(file);
                int available = fileInputStream.available(); //返回与之关联的文件的字节数
                Log.e("字节数---", available + "");
                OkHttpClient httpClient = new OkHttpClient();
                MediaType mediaType = MediaType.parse("image/png");//设置类型
                RequestBody requestBody = RequestBody.create(mediaType, file);//把文件与类型放入请求体
                Request request = new Request.Builder()
                        .url(url)
                        .put(requestBody)
                        .build(); //创建OkHttpClient对象
                Call call = httpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("TAG-失败：", e.toString() + "");
                        dismissProgressDialog();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String string = response.body().toString();
                        Log.e("minio成功---", string + "");
                        uploadFileTb(imgPath, available + "");
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();


    }

    /**
     * 上传照片到服务器数据库
     *
     * @time 2020/12/2 9:55
     */
    private void uploadFileTb(String imgPathSel, String available) {
        // bucket:   1-病历 2-评论(反馈) 3-头像 4-轮播图 9-聊天图片 ',
        // type:   15-病历 2-评论(反馈) 30-头像 92-聊天图片 ',
        RestProxy.getInstance().uploadFileTb("9", "92", resourceId, doctorId, available, "1", new Observer<PicUploadResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(PicUploadResponse picUploadResponse) {
                try {
                    runOnUiThread(() -> {
                        checkServiceRunning(mContext);
                        dialog.dismiss();
                        ChatResponse.Message message = new ChatResponse().new Message();
                        @SuppressLint("SimpleDateFormat") SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                        message.messageType = 1;
                        message.fromType = 1;
                        message.content = picUploadResponse.data.shareThumbnailUrl;
                        message.src = picUploadResponse.data.shareUrl;
                        message.sendTime = df.format(new Date());
                        messageList.add(0, message);
                        chatAdapter.notifyItemInserted(0);
                        rvChat.scrollToPosition(0);
                        nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);//滚动到底部
                        WebSocket webSocket = new WebSocket.Builder().content(picUploadResponse.data.shareThumbnailUrl).docId(doctorId).diagnoseId(diagnoseId).from(BaseApplication.currentUserId).to(patientUserId).picType("jpeg").src(picUploadResponse.data.shareUrl).msgType(1).eventFlag(1).clientId(TimeUtil.getClientId()).build();
                        EventBus.getDefault().postSticky(webSocket);
                    });

                } catch (Exception e) {
                    // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    e.printStackTrace();
                    //打印出来就Log.e(TAG,Log.getStackTraceString(e));
                }

            }

            @Override
            public void onError(Throwable e) {

                ToastUtil.onError(ConsultOrderChatActivity.this, e);
            }

            @Override
            public void onComplete() {
//                dialog.dismiss();
            }
        });
    }


    @SuppressLint("CheckResult")
    private void checkVoicePermission() {
        ApplyPermissionDialog applyPermissionDialog = ApplyPermissionDialog.newInstance("4", true);
        applyPermissionDialog.show(getSupportFragmentManager(), "applyPermissionDialog");
        applyPermissionDialog.setmListener(new ApplyPermissionDialog.OnItemClickListener() {

            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onConfirm() {
                RxPermissions permissions = new RxPermissions(ConsultOrderChatActivity.this);
                permissions.request(VOICEPERMISSIONS)
                        .subscribe(granted -> {
                            if (granted) {
                                if (btn_yuyin.getVisibility() == View.GONE) {
                                    btn_yuyin.setVisibility(View.VISIBLE);
                                    edtContent.setVisibility(View.GONE);
                                    SoftKeyboardUtil.hideSoftKeyboard(mContext);
                                } else {
                                    btn_yuyin.setVisibility(View.GONE);
                                    edtContent.setVisibility(View.VISIBLE);
                                    edtContent.requestFocus();
                                }
                            } else {
                                ToastUtil.showToast(mContext, "请同意语音和存储权限，否则功能无法使用");
                                startNotificationSetting(mContext);
                            }
                        });
            }

            @Override
            public void onCancel() {

            }
        });
    }

    @SuppressLint("CheckResult")
    private void getPermission() {
        ApplyPermissionDialog applyPermissionDialog = ApplyPermissionDialog.newInstance("3", true);
        applyPermissionDialog.show(getSupportFragmentManager(), "applyPermissionDialog");
        applyPermissionDialog.setmListener(new ApplyPermissionDialog.OnItemClickListener() {

            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onConfirm() {
                RxPermissions permissions = new RxPermissions(ConsultOrderChatActivity.this);
                permissions.request(PERMISSIONS)
                        .subscribe(granted -> {
                            if (granted) {
                                //已经打开权限
                                showSelectHeadPicDialog();
                            } else {
                                ToastUtil.showToast(mContext, "请同意相册和存储权限，否则功能无法使用");
                                startNotificationSetting(mContext);
                            }
                        });
            }

            @Override
            public void onCancel() {

            }
        });
    }

    private void showLogoutDialog() {
        mFinishDialog = FinishDialog.newInstance();
        mFinishDialog.show(getSupportFragmentManager(), "mFinishDialog");
        mFinishDialog.setmListener(new FinishDialog.OnItemClickListener() {

            @Override
            public void onConfirm() {
                consultOrderFinish();
            }

            @Override
            public void onCancel() {
                mFinishDialog.dismiss();
                if (mFinishDialog != null) {
                    mFinishDialog = null;
                }
            }
        });
    }

    private void showLogoutDialog2() {
        mFinish2Dialog = Finish2Dialog.newInstance();
        mFinish2Dialog.show(getSupportFragmentManager(), "mFinish2Dialog");
        mFinish2Dialog.setmListener(new Finish2Dialog.OnItemClickListener() {

            @Override
            public void onConfirm() {
                acceptConsultOrder();
                mFinish2Dialog.dismiss();
                if (mFinish2Dialog != null) {
                    mFinish2Dialog = null;
                }
            }

            @Override
            public void onCancel() {
                refuseConsultOrder();
                mFinish2Dialog.dismiss();
                if (mFinish2Dialog != null) {
                    mFinish2Dialog = null;
                }
            }
        });
    }
}
